package com.wkt.ggkt.vod.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wkt.ggkt.exception.GgktException;
import com.wkt.ggkt.model.vod.Course;
import com.wkt.ggkt.model.vod.CourseDescription;
import com.wkt.ggkt.model.vod.Subject;
import com.wkt.ggkt.model.vod.Teacher;
import com.wkt.ggkt.vo.vod.CourseFormVo;
import com.wkt.ggkt.vo.vod.CoursePublishVo;
import com.wkt.ggkt.vo.vod.CourseQueryVo;
import com.wkt.ggkt.vod.mapper.CourseMapper;
import com.wkt.ggkt.vod.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author wkt
 * @since 2022-07-05
 */
@Service
@Slf4j
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private CourseDescriptionService descriptionService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private ChapterService chapterService;

    private static final Logger logger = LoggerFactory.getLogger(CourseServiceImpl.class);
    @Override
    public Map<String, Object> findPageCourse(Page<Course> pageParam, CourseQueryVo courseQueryVo) {

        //获取条件值
        String title = courseQueryVo.getTitle();//名称
        Long subjectId = courseQueryVo.getSubjectId();//二级分类
        Long subjectParentId = courseQueryVo.getSubjectParentId();//一级分类
        Long teacherId = courseQueryVo.getTeacherId();//讲师
        //封装条件
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(title)) {
            wrapper.like("title",title);
        }
        if(subjectId != null) {
            wrapper.eq("subject_id",subjectId);
        }
        if(subjectParentId != null) {
            wrapper.eq("subject_parent_id",subjectParentId);
        }
        if(teacherId != null) {
            wrapper.eq("teacher_id",teacherId);
        }
        wrapper.orderByDesc("create_time");
        //调用方法查询
        Page<Course> pages = baseMapper.selectPage(pageParam, wrapper);
        long totalCount = pages.getTotal();//总记录数
        long totalPage = pages.getPages();//总页数
        long currentPage = pages.getCurrent();//当前页
        long size = pages.getSize();//每页记录数
        //每页数据集合
        List<Course> records = pages.getRecords();
        //遍历封装讲师和分类名称
        records.stream().forEach(item -> {
            this.getTeacherOrSubjectName(item);
        });
        //封装返回数据
        Map<String,Object> map = new HashMap<>();
        map.put("totalCount",totalCount);
        map.put("totalPage",totalPage);
        map.put("records",records);
        return map;
    }

    /**
     * 新增课程信息
     * @param courseFormVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveCourseInfo(CourseFormVo courseFormVo) {
        log.info("courseFormVo入参：", JSON.toJSONString(courseFormVo));
        Course course = new Course();
        BeanUtils.copyProperties(courseFormVo,course);
        if (org.apache.commons.lang3.StringUtils.isBlank(course.getCover())) {
            course.setCover("");
        }
        int insert = baseMapper.insert(course);
        if (insert > 0){
           log.info("课程信息添加成功");
        }

        //设置课程描述信息
        CourseDescription description = new CourseDescription();
        description.setCourseId(course.getId());
        description.setDescription(courseFormVo.getDescription());
        boolean save = descriptionService.save(description);
        if (save) {
            log.info("课程描述信息添加成功");
        }

        return course.getId();
    }

    /**
     * 根据课程id查询课程信息
     * @param id
     * @return
     */
    @Override
    public CourseFormVo getCourseById(Long id) {
        Course course = baseMapper.selectById(id);
        if (course == null){
            throw new GgktException(404,"课程信息为空！");
        }
        QueryWrapper<CourseDescription> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",course.getId());
        CourseDescription courseDescription = descriptionService.getOne(queryWrapper);

        //封装CourseFormVo
        CourseFormVo courseFormVo = new CourseFormVo();
        BeanUtils.copyProperties(course,courseFormVo);
        if (courseDescription != null){
            courseFormVo.setDescription(courseDescription.getDescription());
        }
        return courseFormVo;
    }

    /**
     * 修改课程信息
     * @param courseFormVo
     * @return
     */
    @Override
    public int updateCourseById(CourseFormVo courseFormVo) {
        Course course = new Course();
        BeanUtils.copyProperties(courseFormVo, course);
        int i = baseMapper.updateById(course);
        if (i > 0){
            logger.info("修改课程信息成功!");
        }
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseFormVo.getDescription());

        QueryWrapper<CourseDescription> update = new QueryWrapper<>();
        update.eq("course_id",courseFormVo.getId());
        descriptionService.update(courseDescription,update);
        return i;
    }

    /**
     * 获取讲师和分类名称
     * @param course
     * @return
     */
    private Course getTeacherOrSubjectName(Course course) {
        //查询讲师名称
        Teacher teacher = teacherService.getById(course.getTeacherId());
        if(teacher != null) {
            course.getParam().put("teacherName",teacher.getName());
        }
        //查询分类名称
        Subject subjectOne = subjectService.getById(course.getSubjectParentId());
        if(subjectOne != null) {
            course.getParam().put("subjectParentTitle",subjectOne.getTitle());
        }
        Subject subjectTwo = subjectService.getById(course.getSubjectId());
        if(subjectTwo != null) {
            course.getParam().put("subjectTitle",subjectTwo.getTitle());
        }
        return course;
    }

    /**
     * 根据课程id查询课程发布信息
     * @param id
     * @return
     */
    @Override
    public CoursePublishVo getPublishCourseVo(Long id) {
        return baseMapper.getPublishCourseVoByCourseId(id);
    }

    @Override
    public void publishCourse(Long id) {
        Course course = baseMapper.selectById(id);
        course.setStatus(1);
        course.setPublishTime(LocalDateTime.now());
        baseMapper.updateById(course);
    }

    @Override
    public void removeCourse(Long id) {
        // 删除课程视频信息
        videoService.removeCourseByCourseId(id);
        //删除章节信息
        chapterService.removeCourseByCourseId(id);
        //删除课程描述信息
        descriptionService.removeCourseByCourseId(id);
        //删除课程信息
        baseMapper.deleteById(id);
    }
}
